package com.zzyl.nursing.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.DeviceDataPageReqDto;
import com.zzyl.nursing.mapper.DeviceDataMapper;
import com.zzyl.nursing.service.IDeviceDataService;
import com.zzyl.nursing.service.IDeviceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 设备数据Service业务层处理
 * 
 * @author zzyl
 * @date 2025-10-25
 */
@Service
public class DeviceDataServiceImpl extends ServiceImpl<DeviceDataMapper, DeviceData> implements IDeviceDataService
{
    @Autowired
    private DeviceDataMapper deviceDataMapper;

    /**
     * 查询设备数据
     * 
     * @param id 设备数据主键
     * @return 设备数据
     */
    @Override
    public DeviceData selectDeviceDataById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询设备数据列表
     * 
     * @param deviceData 设备数据
     * @return 设备数据
     */
    @Override
    public List<DeviceData> selectDeviceDataList(DeviceDataPageReqDto deviceData)
    {
        return null;
    }

    /**
     * 新增设备数据
     * 
     * @param deviceData 设备数据
     * @return 结果
     */
    @Override
    public int insertDeviceData(DeviceData deviceData)
    {
        return save(deviceData) ? 1 : 0;
    }

    /**
     * 修改设备数据
     * 
     * @param deviceData 设备数据
     * @return 结果
     */
    @Override
    public int updateDeviceData(DeviceData deviceData)
    {
        return updateById(deviceData) ? 1 : 0;
    }

    /**
     * 批量删除设备数据
     * 
     * @param ids 需要删除的设备数据主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除设备数据信息
     * 
     * @param id 设备数据主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataById(Long id)
    {
        return removeById(id) ? 1 : 0;
    }

    @Autowired
    private IDeviceService deviceService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public void saveBatchData(IotMsgNotifyData iotMsgNotifyData) {
        //1.查询数据库中是否有此设备
        IotMsgHeader header = iotMsgNotifyData.getHeader();
        Device device = deviceService.lambdaQuery()
                .eq(Device::getIotId, header.getDeviceId())
                .one();
        if (device == null) {
            throw new BaseException("此设备不存在");
        }
        //2.构建设备数据
        ArrayList<DeviceData> deviceDataList = new ArrayList<>();
        IotMsgBody body = iotMsgNotifyData.getBody();
        List<IotMsgService> serviceList = body.getServices();
        //格式化时间 ，原格式为：20251025T022515Z
        serviceList.forEach(x -> {
            String eventTime = x.getEventTime();
            LocalDateTime alarmTime = OffsetDateTime.parse(eventTime, DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmssX"))
                    .atZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                    .toLocalDateTime();
            x.getProperties().forEach((k,v) -> {
                DeviceData deviceData = DeviceData.builder()
                        .deviceName(device.getDeviceName())
                        .iotId(header.getDeviceId())
                        .nodeId(header.getNodeId())
                        .nickname(device.getNickname())
                        .productKey(device.getProductKey())
                        .productName(device.getProductName())
                        .functionId(k)
                        .dataValue(String.valueOf(v))
                        .accessLocation(device.getBindingLocation())
                        .locationType(device.getLocationType())
                        .physicalLocationType(device.getPhysicalLocationType())
                        .deviceDescription(device.getDeviceDescription())
                        .alarmTime(alarmTime)
                        .build();
                deviceDataList.add(deviceData);
            });
        });
        //3.批量保存
        this.saveBatch(deviceDataList);

        //4.保存到redis中
        redisTemplate.opsForHash().put(CacheConstants.IOT_DEVICE_LAST_DATA_LATEST,device.getIotId(),deviceDataList);
    }

    @Override
    public Page<DeviceData> pageList(DeviceDataPageReqDto dto) {
        Page<DeviceData> page = this.lambdaQuery()
                .eq(StrUtil.isNotBlank(dto.getDeviceName()), DeviceData::getDeviceName, dto.getDeviceName())
                .eq(StrUtil.isNotBlank(dto.getFunctionId()), DeviceData::getFunctionId, dto.getFunctionId())
                .between(dto.getStartTime() != null && dto.getEndTime() != null, DeviceData::getAlarmTime, dto.getStartTime(), dto.getEndTime())
                .orderByDesc(DeviceData::getAlarmTime)
                .page(Page.of(dto.getPageNum(), dto.getPageSize()));
        return page;
    }
}
